<template>
  <div>
    <div>
      <label>用户名:</label><BaseInput v-model.trim="mobile" ref="useIpt" />
    </div>
    <div>
      <label>密码:</label
      ><BaseInput
        @keyup.native.enter="doLogin"
        v-model.trim="pwd"
        type="password"
      />
    </div>
    <div class="bottom-box">
      <BaseCheckBox v-model="isRem">记住账号</BaseCheckBox>
      <div class="right-content">
        <BaseButton @click="doLogin" type="success">登录</BaseButton>
      </div>
    </div>
  </div>
</template>

<script>
// 导入axios
import axios from "axios";

export default {
  name: "LoginBox",
  data() {
    return {
      isRem: false,
      mobile: "18888888888",
      pwd: "246810",
    };
  },
  methods: {
    getFocus() {
      this.$refs.useIpt.focus();
    },

    async doLogin(e) {
      // // console.log(e.currentTarget) // 绑定事件的元素
      // // console.log(e.target) // 真正触发事件的元素
      // // 1. 判断账号和密码是否正确
      // if (this.mobile == '18888888888' && this.pwd == '246810') {
      //   alert('登录成功')
      //   // 假装发了请求，再假装服务器已经返回了token
      //   // 我们就把token存起来
      //   localStorage.setItem('token', 'dfdshjf-fgdfgfdgfd-fgdghfhgf-dsdfs')
      //   this.$router.push('/layout')
      // }else {
      //   alert('账号或密码错误')
      // }

      // 直接.then和.catch
      /*
      axios({
        url: 'https://toutiao.itheima.net/v1_0/authorizations',
        method: 'post',
        data: {
          mobile: this.mobile,
          code: this.pwd
        }
      })
      .then( res => {

        // 登录成功，弹出提示
        alert('登录成功！')
        // 保存token
        localStorage.setItem('token', res.data.data.token)
        // 跳转
        this.$router.push('/layout/home')
      })
      .catch(err => {

        alert('账号或密码错误')
      })
    */

      // 使用async加await
      try {
        let res = await axios({
          url: "https://toutiao.itheima.net/v1_0/authorizations",
          method: "post",
          data: {
            mobile: this.mobile,
            code: this.pwd,
          },
        });

        // 登录成功，弹出提示
        alert('登录成功！')
        // 保存token
        localStorage.setItem('token', res.data.data.token)
        // 跳转
        this.$router.push('/layout/home')

      } catch (err) {

        alert('账号或密码错误')
      }
    },
  },
  mounted() {
    this.getFocus();
  },
  activated() {
    this.getFocus();
  },
};
</script>

<style scoped lang="less">
.bottom-box {
  display: flex;
  justify-content: space-between;
  padding: 0 40px;
  padding-left: 90px;
}
.login-title {
  color: #252526;
  font-weight: normal;
}

label {
  display: inline-block;
  width: 60px;
  text-align: right;
}
</style>
